﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace BasecampSync
{
    public partial class FrmSettings : Form
    {
        public FrmSettings()
        {
            InitializeComponent();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            string errorMsg = "";

            if (TxtUsername.Text.Trim() == "")
            {
                errorMsg = "Please enter a Username.";
            }

            if (TxtPassword.Text.Trim() == "")
            {
                errorMsg = "Please enter a Password.";
            }

            if (TxtUrl.Text.Trim() == "")
            {
                errorMsg = "Please enter a basecamp url.";
            }
            else
            {
                Regex testUrl = new Regex("http://*.?");

                if (!testUrl.IsMatch(TxtUrl.Text))
                {
                    errorMsg = "Please enter a valid url.";
                }
                else
                {
                    // Url has to contain a trailling slash
                    if (!TxtUrl.Text.EndsWith("/"))
                    {
                        TxtUrl.Text += "/";
                    }
                }
            }

            if (errorMsg != "")
            {
                MessageBox.Show(errorMsg);
            }
            else
            {
                Config.BasecampPassword = TxtPassword.Text.Trim();
                Config.BasecampUsername = TxtUsername.Text.Trim();
                Config.BasecampUrl = TxtUrl.Text.Trim();
                Config.Save();  
                this.Close();
            }
        }

        private void FrmSettings_Load(object sender, EventArgs e)
        {
            Config.Load();
            TxtUsername.Text = Config.BasecampUsername;
            TxtPassword.Text = Config.BasecampPassword;
            TxtUrl.Text = Config.BasecampUrl;
        }
    }
}
